# Controller for the Archive page, showing categories and documents.
class CategoriesController < ApplicationController
	
	include SortHelper
	
	helper_method :sort_options
	skip_before_filter :require_logged_in, only: [:index, :show]
	
	def index
		# Default value for sorting
		@sort_by = params[:sort_by] || '#.created_at'
		@direction = params[:direction] || 'desc'
		
		# Display all documents on archive index page
		@latest_documents = Document.with_translations
			.paginate(page: params[:page], per_page: 15)
			.order(sort_order(@sort_by, Document, @direction))
			.search(params[:search])
	end
	
	def show
		@category = Category.find(params[:id])
		
		if params[:search].blank?
			@documents = Document.with_translations.joins(:categories)
					.where('categories_documents.category_id IN (?)', @category.subtree_ids)
		else
			# Search only through current locale
			@documents = Document.with_translations(I18n.locale)
				.search(params[:search], @category.subtree_ids)
		end
				
		# Default value for sorting
		@sort_by = params[:sort_by] || 'name'
		@direction = params[:direction] || 'asc'
		
		@documents = @documents.order(sort_order(@sort_by, Document, @direction))
			.paginate(page: params[:page])
	end

	private 
	
	def sort_options
		AComposite.sort_options
	end
	
end
